package com.shell.customer.accreditation.rx;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.cfca.CfcaConfiguration;
import com.shell.bee.cfca.paperless.request.CfcaSignRequest;
import com.shell.bee.cfca.paperless.response.BaseResponse;
import com.shell.bee.cfca.paperless.service.CfcaSignTxService;
import com.shell.bee.contract.ContService;
import com.shell.bee.contract.po.ContBas;
import com.shell.bee.contract.po.ContProt;
import com.shell.bee.contract.po.ContTmpl;
import com.shell.bee.esign.po.EsCust;
import com.shell.bee.esign.service.EsCustService;
import com.shell.bee.esign.service.EsignSealService;
import com.shell.bee.esign.service.EsignSignService;
import com.shell.bee.esign.vo.SingleSignVo;
import com.shell.bee.report.utils.FilePathHelper;
import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.accreditation.vo.UserVo;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.esign.service.EsignAcctTxService;
import com.shell.customer.po.CusRec;
import com.shell.customer.util.CustomerUtil;
import com.shell.feign.PubUserFeign;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.governor.user.po.PubUser;
import com.timevale.esign.sdk.tech.bean.result.AddSealResult;
import com.timevale.esign.sdk.tech.bean.result.AddAccountResult;
import com.timevale.esign.sdk.tech.bean.result.FileDigestSignResult;
import com.timevale.esign.sdk.tech.bean.seal.OrganizeTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.PersonTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.SealColor;
import java.io.File;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ContSignSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private EsCustService esCustService;
	@Autowired
	private EsignSealService esignSealService;
	@Autowired
	private ContService contService;
	@Autowired
	private EsignSignService esignSignService;
	@Autowired
	private EsignAcctTxService esignAcctTxService;
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	private PubUserFeign pubUserFeign;
	@Autowired
	private CfcaSignTxService cfcaSignTxService;

	public void onApplicationEvent(AccreditEvent event) {
		ContBas cont = (ContBas) event.getValue("cont");
		String entId = CommonDataUtil.getCurEntId();
		AccreditationVo accreditationVo = event.getAccreditationVo();
		CusRec cus = accreditationVo.getCustomerC();
		if (cont == null) {
			List<ContBas> conts = this.contService.selectConts(cus.getCusId(), "20", null);
			if ((conts != null) && (conts.size() > 0)) {
				cont = (ContBas) conts.get(0);
			} else {
				throw new UnCheckMsgException("����������");
			}
		}
		if ((CustomerUtil.onEsign()) || (CustomerUtil.onCfca())) {
			ContProt contProt = null;
			ContTmpl contTmpl = null;
			List<ContProt> prots = this.contService.selectProts(cont.getContId());
			if ((prots != null) && (prots.size() > 0)) {
				contProt = (ContProt) prots.get(0);
				contTmpl = this.contService.selectContTmplByKey(contProt.getTmplId());
			}
			if (contProt == null) {
				throw new UnCheckMsgException("����������");
			}
			if (CustomerUtil.onEsign()) {
				signByEsign(accreditationVo, cont, contProt, contTmpl);
			} else if (CustomerUtil.onCfca()) {
				signByCfca(accreditationVo, cont, contProt, contTmpl);
			}
		}
		if (entId.equals(cont.getSponsor())) {
			cont.setContState("3");
		} else {
			CusRec platform = getPlatform();
			entId = platform.getCusId();
			cont.setContState("6");
			cont.setContProgress("1");
		}
		this.contService.sign(cont, entId);
	}

	private void signByCfca(AccreditationVo accreditationVo, ContBas cont, ContProt contProt, ContTmpl contTmpl) {
		String entId = CommonDataUtil.getCurEntId();
		CusRec cus = accreditationVo.getCustomerC();
		UserVo user = accreditationVo.getAdministrator();
		CfcaSignRequest request = new CfcaSignRequest();
		if (entId.equals(cont.getSponsor())) {
			if ("3".equals(cont.getContState())) {
				return;
			}
			cont.setContState("3");

			request.setUserId(user.getUserId());
			request.setUserName(user.getUserName());
			request.setIdNo(user.getCertNo());
			request.setPhoneNo(user.getPhoneNo());
			request.setPhoneCode(accreditationVo.getPhoneCode());
			request.setCusId(entId);
			request.setCusName(cus.getCusName());
			request.setLocation(accreditationVo.getLocation());
			request.setReason("������������");
			request.setSignPage(Integer.parseInt(contTmpl.getSponsorPage()));
			request.setKey(cus.getCusName());
			request.setKeyIndex(contTmpl.getSponsorKeyIndex());
		} else {
			CusRec platform = getPlatform();
			String userId = platform.getContactorId();
			PubUser pubUser = this.pubUserFeign.selectByKey(userId);
			request.setUserId(pubUser.getUserId());
			request.setUserName(pubUser.getUserName());
			request.setIdNo(pubUser.getCertNo());
			request.setPhoneNo(pubUser.getPhoneNo());

			request.setCusId(platform.getCusId());
			request.setCusName(platform.getCusName());

			request.setReason("������������");
			request.setSignPage(Integer.parseInt(contTmpl.getAcceptorPage()));
			request.setKey(platform.getCusName());
			request.setKeyIndex(contTmpl.getAcceptorKeyIndex());
			request.setSendSms(false);
			request.setSealCode(CfcaConfiguration.getCfcaBankSealCode());
		}
		request.setContId(cont.getContId());
		request.setSrcPdfPath(contProt.getProtLoc());
		request.setDestPdfPath(contProt.getProtLoc());
		BaseResponse response = this.cfcaSignTxService.sign(request);
		if (!response.isSuccess()) {
			throw new UnCheckMsgException("��������������cfca��" + response.getMessage());
		}
	}

	private void signByEsign(AccreditationVo accreditationVo, ContBas cont, ContProt contProt, ContTmpl contTmpl) {
		String entId = CommonDataUtil.getCurEntId();
		CusRec cus = accreditationVo.getCustomerC();
		UserVo admin = accreditationVo.getAdministrator();
		if (entId.equals(cont.getSponsor())) {
			if ("3".equals(cont.getContState())) {
				return;
			}
			cont.setContState("3");

			SingleSignVo singleSignVo = getSingleSignVo(admin, cus, cont, contProt, contTmpl,
					accreditationVo.getPhoneCode());
			FileDigestSignResult result = this.esignSignService.sign(singleSignVo);
			if (result.getErrCode() != 0) {
				throw new UnCheckMsgException("��������������e������" + result.getMsg());
			}
			updateContProt(contProt, singleSignVo);
		} else {
			CusRec platform = getPlatform();
			EsCust esCust = (EsCust) this.esCustService.selectByKey(platform.getCusId());
			String acctId;
			if (esCust == null) {
				PubUser pubUser = this.pubUserFeign.selectByKey(platform.getContactorId());
				UserVo userVo = new UserVo();
				userVo.setUserName(pubUser.getUserName());
				userVo.setCertNo(pubUser.getCertNo());
				AddAccountResult result = this.esignAcctTxService.openCustAcct(platform, userVo);
				acctId = result.getAccountId();
			} else {
				acctId = esCust.getAcctId();
			}
			AddSealResult seal = this.esignSealService.getOrganizeSeal(acctId, OrganizeTemplateType.STAR, SealColor.RED,
					"", "");
			FileDigestSignResult result = this.esignSignService.sign(acctId, seal.getSealData(), contProt.getProtLoc(),
					contTmpl.getAcceptorPage(), "��" + platform.getCusName(), cont.getContId(), platform.getCusId());
			if (result.getErrCode() != 0) {
				result = this.esignSignService.sign(acctId, seal.getSealData(), contProt.getProtLoc(),
						contTmpl.getAcceptorPage(), ":" + platform.getCusName(), cont.getContId(), platform.getCusId());
				if (result.getErrCode() != 0) {
					throw new UnCheckMsgException("��������������e������" + result.getMsg());
				}
			}
		}
	}

	private void updateContProt(ContProt contProt, SingleSignVo singleSignVo) {
		this.contService.updateProtLoc(contProt.getProtId(), singleSignVo.getDestPdfPath());
		File tmp = new File(singleSignVo.getSrcPdfPath());
		if (tmp.exists()) {
			tmp.delete();
		}
	}

	private SingleSignVo getSingleSignVo(UserVo admin, CusRec cus, ContBas cont, ContProt contProt, ContTmpl contTmpl,
			String phoneCode) {
		String pdfSrcPath = contProt.getProtLoc();
		String pdfDestPath = FilePathHelper.replaceFileName(pdfSrcPath, SystemUtil.getUUID(), "pdf");

		EsCust esCust = null;
		AddSealResult seal = null;
		if ("PERSONAL".equals(cus.getCusType())) {
			esCust = (EsCust) this.esCustService.selectByKey(admin.getUserId());
			seal = this.esignSealService.getPersonSeal(esCust.getAcctId(), PersonTemplateType.RECTANGLE, SealColor.RED);
		} else {
			esCust = (EsCust) this.esCustService.selectByKey(cus.getCusId());
			seal = this.esignSealService.getOrganizeSeal(esCust.getAcctId(), OrganizeTemplateType.STAR, SealColor.RED,
					"", "");
		}
		SingleSignVo singleSignVo = new SingleSignVo();
		singleSignVo.setAcctId(esCust.getAcctId());
		singleSignVo.setSealData(seal.getSealData());
		singleSignVo.setKey(cus.getCusName());
		singleSignVo.setCustId(cus.getCusId());
		singleSignVo.setSrcPdfPath(contProt.getProtLoc());
		singleSignVo.setDestPdfPath(pdfDestPath);
		singleSignVo.setPhoneNo(admin.getPhoneNo());
		singleSignVo.setPhoneCode(phoneCode);
		singleSignVo.setSignPage(contTmpl.getSponsorPage());
		singleSignVo.setProtId(contProt.getProtId());
		singleSignVo.setContId(cont.getContId());
		return singleSignVo;
	}

	private CusRec getPlatform() {
		CusRec platform = this.cusRecService.getPlatform(null);
		if (platform == null) {
			throw new UnCheckMsgException("����������������");
		}
		return platform;
	}
}
